/*
 * Copyright (c) 2014, S.F. Express Inc. All rights reserved.
 */
package org.jasig.cas.client.util;

import java.io.FileInputStream;
import java.net.URL;
import java.util.Properties;

import javax.servlet.FilterConfig;

/**
 * 描述：配置文件工具类
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID   DATE            PERSON          REASON
 *  1    2015年12月23日     014767          Create
 * ****************************************************************************
 * </pre>
 * 
 * @author 014767
 * @since 1.0
 */
public class ConfigUtils {

    private static final String PARAM_CONFIG = "cas-config";
    private static final String DEFAULT_CONFIG = "classpath:config.properties";
    private static Properties properties;
    private static Boolean hasConfig = null;

    public static String getConfig(FilterConfig filterConfig, String propertyName) {
        if (hasConfig == null) {
            synchronized (ConfigUtils.class) {
                if (hasConfig == null) {
                    try {
                        properties = initProperties(filterConfig);
                        hasConfig = true;
                    } catch (Exception e) {
                        hasConfig = false;
                    }
                }
            }
        }
        
        if (Boolean.TRUE.equals(hasConfig)) {
            return properties.getProperty(propertyName);
        } else {
            return null;
        }
    }

    private static Properties initProperties(FilterConfig filterConfig) {
        String configFile = filterConfig.getServletContext().getInitParameter(PARAM_CONFIG);
        if (configFile == null) {
            configFile = DEFAULT_CONFIG;
        }

        FileInputStream fis = null;
        try {
            try {
                fis = new FileInputStream(getRealFileName(filterConfig, configFile));
                Properties properties = new Properties();
                properties.load(fis);
                return properties;
            } finally {
                if (fis != null) {
                    fis.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("load config file error: " + configFile, e);
        }
    }

    private static String getRealFileName(FilterConfig filterConfig, String file) {
        if (file.startsWith("classpath")) {
            int index = file.indexOf(':');
            if (index != -1) {
                file = file.substring(index + 1);
            }

            URL url = ConfigUtils.class.getClassLoader().getResource(file);
            if (url == null) {
                throw new RuntimeException("can not load config: " + file);
            }
            file = url.getPath();
        } else if (file.startsWith("file")) {
            int index = file.indexOf(':');
            if (index != -1) {
                file = file.substring(index + 1);
            }
        } else if (file.startsWith("/WEB-INF/")) {
            file = filterConfig.getServletContext().getRealPath(file);
        } else if (file.startsWith("${")) {
            file = getEnvConfigFileName(file);
        }

        return file;
    }

    private static String getEnvConfigFileName(String file) {
        int index = file.indexOf('}');
        String envParam = file.substring(2, index);
        file = file.substring(index + 1);
        String configPath = System.getenv(envParam);
        if (configPath == null) {
            throw new RuntimeException("can not find config path in system environment: " + envParam);
        }

        if (!configPath.endsWith("/")) {
            configPath = configPath + "/";
        }
        if (file.startsWith("/")) {
            file = file.substring(1);
        }
        return configPath + file;
    }
}
